/*
 * @Author: 涵崽
 * @Date: 2023-11-06 10:03:46
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2023-11-10 14:06:07
 * @Description: 防抖函数(该方法中如果a,b两个按钮同时绑定了这个指令，b按钮不会收到a按钮的影响)
 *
 * 使用方法：在mian.js中引入
 *
 * <button v-debounce="{ fn: clickbtn1, event: 'click', time: 1000 }">按钮</button>
     <input v-debounce="{fn: clickbtn, event: 'input', time: 500}" />
 */

const debounce = {
  inserted: function (el, { value: { fn, event, time } }) {
    //没绑定函数直接返回
    if (typeof fn !== "function") return;
    el._timer = null;
    //监听点击事件，限定事件内如果再次点击则清空定时器并重新定时
    el.addEventListener(event, () => {
      if (el._timer !== null) {
        clearTimeout(el._timer);
        el._timer = null;
      }
      el._timer = setTimeout(() => {
        fn();
      }, time);
    });
  },
};

export default debounce;
